package com.rd.sys.common.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.web.session.SessionUtil;
import com.rd.sys.dto.sys.user.UserInfoDto;

public class UserLoginFilter implements Filter {
    private String loginPageUrl;

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;

            /* 当Session不为空且存在用户信息时,才允许通过 */
            HttpSession session = SessionUtil.getSession(req);
            if (session != null) {
                UserInfoDto userInfo = (UserInfoDto) session
                        .getAttribute(CommonConstants.UserConstats.USER_SESSION_FLAG);
                if (userInfo != null) {
                    chain.doFilter(request, response);
                    return;
                }
            }
            String host = "http://" + req.getHeader("Host");
            res.sendRedirect(host + req.getContextPath() + loginPageUrl);

        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        loginPageUrl = filterConfig.getInitParameter("loginPage");
    }

}
